package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"zhhuiyan/models"
	. "zhhuiyan/authority"
	. "zhhuiyan/db"
	"time"
	"code.google.com/p/go-uuid/uuid"
)

type ArticleController struct {
	beego.Controller
}

func (this *ArticleController) Set(tpl string) {
	this.Data["Path"] = "article"
	this.Layout = "layout.html"
	this.TplNames = "article/"+tpl
}
func (this *ArticleController) Get() {
	id, _ := this.GetInt(":objectId")
	var model = &models.Article{Id:id, Object:&Object{Id:id}}
	if id != 0 {
		if err := Handler.Read(model); err != nil {
			fmt.Println(err)
		}
		if (model.Object != nil) {
			if err := Handler.Read(model.Object); err != nil {
				fmt.Println(err)
			}
		}
		tp := this.GetString("type")
		this.Data["Model"] = model
		if (tp != "") {
			this.Set(tp + ".html")
		}else {
			this.Set("show.html")
		}

		return
	}
	page := &models.Page{Size:20 }
	models := *new([]models.Article)
	if err := List("article", page, &models); err != nil {
		fmt.Println(err)
	}
	this.Data["Page"] = page
	this.Data["Models"] = models
	this.Set("list.html")
}
func (this *ArticleController) Add() {
	this.Data["Model"] = &models.Article{ Object:&Object{}}
	this.Set("add.html")
}
func (this *ArticleController) Post() {
	object := &Object{Name: uuid.New()}
	if _, err := Handler.Insert(object) ; err != nil {
		fmt.Println("object:", err)
	}
	model := &models.Article{Title:this.GetString("title"),
		Summary:this.GetString("title"),
		Content:this.GetString("content"),
		CreateTime:time.Now(),
		Object:object}
	if _, err := Handler.Insert(model) ; err != nil {
		fmt.Println("Article.persis:", err)
	}
	this.Data["Model"] = model
	this.Set("show.html")
}

func (this *ArticleController) Edit() {
	this.Set("show.html")
}

